package com.yeban.javase.day19.answer.test4;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.LockSupport;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/11/4
 */
public class ReadThread implements Runnable{

    private Socket socket;
    private CountDownLatch countDownLatch;

    public ReadThread(Socket socket, CountDownLatch countDownLatch) {
        this.socket = socket;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        try(
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        ) {
            String str = null;
            while((str = br.readLine()) != null) {
                if(str.equals("exit")) {
                    System.out.println(socket.getRemoteSocketAddress() + "已下线~");
                    break;
                }
                System.out.println(socket.getRemoteSocketAddress() + "说：" + str);
            }
        } catch (SocketException e) {
            System.out.println("客户端异常退出！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            countDownLatch.countDown();
        }
    }
}
